package com.cetool.autocms.service.login.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cetool.autocms.exception.ServiceException;
import com.cetool.autocms.mapper.login.LoginMapper;
import com.cetool.autocms.pojo.domain.login.ClientUserInfoDO;
import com.cetool.autocms.pojo.domain.login.UserInfoDO;
import com.cetool.autocms.pojo.dto.login.ClientUserInfoDTO;
import com.cetool.autocms.pojo.dto.login.UserInfoDTO;
import com.cetool.autocms.pojo.param.login.LoginParam;
import com.cetool.autocms.pojo.request.login.LoginRequest;
import com.cetool.autocms.service.enumeration.LoginExceptionEnum;
import com.cetool.autocms.service.login.LoginService;
import com.cetool.autocms.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * 登陆管理服务实现层
 *
 * @author 戴越
 * @date 2021/11/9
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    /**
     * 注入登陆管理持久层
     */
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public UserInfoDTO adminLogin(LoginRequest request) {
        UserInfoDTO result = new UserInfoDTO();
        LoginParam param = new LoginParam();
        BeanUtil.copyProperties(request, param);
        UserInfoDO userInfoDO = loginMapper.getUser(param);
        if (userInfoDO != null) {
            String md5Passwrod = DigestUtils.md5DigestAsHex((request.getUserName() + request.getPassword()).getBytes()).toUpperCase();
            if (!userInfoDO.getUserPassWord().equals(md5Passwrod)) {
                throw new ServiceException(LoginExceptionEnum.LOGIN_FAILED_PASSWORD_ERROR);
            }
        } else {
            throw new ServiceException(LoginExceptionEnum.LOGIN_FAILED_USER_NOT_EXIST);
        }
        BeanUtil.copyProperties(userInfoDO, result);
        result.setToken(TokenUtil.createToken(userInfoDO));
        return result;
    }

    @Override
    public ClientUserInfoDTO clientLogin(LoginRequest request) {
        ClientUserInfoDTO result = new ClientUserInfoDTO();
        LoginParam param = new LoginParam();
        BeanUtil.copyProperties(request, param);
        ClientUserInfoDO clientUserInfoDO = loginMapper.getClientUser(param);
        if (clientUserInfoDO != null) {
            String md5Passwrod = DigestUtils.md5DigestAsHex((request.getUserName() + request.getPassword()).getBytes()).toUpperCase();
            if (!clientUserInfoDO.getUserPassWord().equals(md5Passwrod)) {
                throw new ServiceException(LoginExceptionEnum.LOGIN_FAILED_PASSWORD_ERROR);
            }
        } else {
            throw new ServiceException(LoginExceptionEnum.LOGIN_FAILED_USER_NOT_EXIST);
        }
        BeanUtil.copyProperties(clientUserInfoDO, result);
        return result;
    }
}
